package base.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Ticket implements Runnable {

    private static int ticketNum=100;
    private Object obj=new Object();

    private Lock lock=new ReentrantLock(true);//true为公平锁，多个线程公平拥有执行权，false非公平锁，为独占锁

    @Override
    public void run() {


    }

    //线程不安全
    private void trains1(){
        while (ticketNum>0){
            try {
                Thread.sleep(100);
                String name=Thread.currentThread().getName();
                System.out.println("线程： "+name+"  销售电影票   "+ticketNum--);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    //线程安全
     private void trains2(){
         while (ticketNum>0){
             synchronized (obj){//这里使用了锁synchronized
                 try {
                     Thread.sleep(100);
                     String name=Thread.currentThread().getName();
                     System.out.println("线程： "+name+"  销售电影票   "+ticketNum--);

                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
         }
    }

    //对于非静态方法的同步锁，锁的对象是this，
    //对于静态方法的同步锁，锁的对象是类名.class
    private synchronized void trains3(){
        while (ticketNum>0){
            try {
                Thread.sleep(100);
                String name=Thread.currentThread().getName();
                System.out.println("线程： "+name+"  销售电影票   "+ticketNum--);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void clockDemo(){
        while (ticketNum>0){
            lock.lock();
            try {
                Thread.sleep(100);
                String name=Thread.currentThread().getName();
                System.out.println("线程： "+name+"  销售电影票   "+ticketNum--);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();//这里一定要进行解锁，否则会发生死锁问题
            }
        }

    }







}
